package com.xhh.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.heima.utils.thread.ThreadLocalUtil;
import com.xhh.model.user.pojos.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author:xhh
 * @email:3231954428@qq.com
 * @desc:
 * @datatime:2024/6/4 20:33
 */
@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取header中的信息
        String userId = request.getHeader("userId");
        if (StrUtil.isNotBlank(userId)) {
            // 把用户id存入到threadLoad中
            User user = new User();
            user.setId(Long.valueOf(userId));
            ThreadLocalUtil.setUser(user);
            log.info("appTokenFilter设置用户信息到threadLoad中...");
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("清理threadLocal....");
        ThreadLocalUtil.clear();
    }
}
